import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:intl/intl.dart';
import 'package:osg/controllers/http.dart';

class WEBhome extends StatefulWidget {
  const WEBhome({super.key});

  @override
  State<WEBhome> createState() => _WEBhome();
}
    late DateTime targetDate;
  Duration remaining = Duration.zero;
  late Timer timer;

class _WEBhome extends State<WEBhome> {
  final RxInt _index = 0.obs;

  RxList SearchData = [].obs;



  bool isExpired(String targetTime) {
  final now = DateTime.now();
  final format = DateFormat('yyyy-MM-dd HH:mm:ss');
  final target = format.parse(targetTime);
  return now.isAfter(target);
}

  getSearch(type) {
    Get.find<HTTPS>()
        .getData('/search', {'item_type': type}).then((res) {


        for (var i = 0; i < res['list'].length; i++) {

          res['list'][i]['istime']=isExpired(res['list'][i]['sell_date']);


             List<String> parts = res['list'][i]['sell_date'].split(' ');


             List<String> dateParts = parts[0].split('-');
             List<String> timeParts = parts[1].split(':');

            

                res['list'][i]['targetDate'] = DateTime(
                  int.parse(dateParts[0]), // 年
                  int.parse(dateParts[1]), // 月
                  int.parse(dateParts[2]), // 日
                  int.parse(timeParts[0]), // 时
                  int.parse(timeParts[1]), // 分
                  int.parse(timeParts[2]) // 秒
                 );

                // targetDate= DateTime(2025, 6, 25, 20, 20, 20);

                //   timer = Timer.periodic(Duration(seconds: 1), (timer) {
                //     remaining = targetDate.difference(DateTime.now());

                //       if (remaining.isNegative) {
                //         remaining = Duration.zero;


                //         timer.cancel();
                //       }
                //   });


               

              }
    
      SearchData.value = res['list'];

      print(SearchData);

    });
  }
 

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    

    WidgetsBinding.instance.addPostFrameCallback((_) {
      getSearch('product');
    });
  }



  @override
  Widget build(BuildContext context) {
    return Container(
       padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
        SizedBox(height: 10),
          CarouselWithDots(),
          SizedBox(
            height: 25,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              GestureDetector(
                onTap: () => {Get.toNamed('/web_tabs/lottery/lottery_draw')},
                child: Column(
                  children: [
                    Image.asset(
                      'static/web/choujiang.png',
                      width: 60,
                      fit: BoxFit.fitWidth,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      '抽奖',
                      style: TextStyle(fontSize: 12),
                    )
                  ],
                ),
              ),
              GestureDetector(
                onTap: () =>
                    {Get.toNamed('/web_tabs/activity/synthesis?type=1')},
                child: Column(
                  children: [
                    Image.asset(
                      'static/web/hecheng.png',
                      width: 60,
                      fit: BoxFit.fitWidth,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      '合成',
                      style: TextStyle(fontSize: 12),
                    )
                  ],
                ),
              ),
              GestureDetector(
                onTap: () =>
                    {Get.toNamed('/web_tabs/activity/synthesis?type=1&jing=2')},
                child: Column(
                  children: [
                    Image.asset(
                      'static/web/zhihuan.png',
                      width: 60,
                      fit: BoxFit.fitWidth,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      '升级',
                      style: TextStyle(fontSize: 12),
                    )
                  ],
                ),
              ),
              GestureDetector(
                onTap: () =>
                    {Get.toNamed('/web_tabs/activity/synthesis?type=2')},
                child: Column(
                  children: [
                    Image.asset(
                      'static/web/fenjie.png',
                      width: 60,
                      fit: BoxFit.fitWidth,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      '分解',
                      style: TextStyle(fontSize: 12),
                    )
                  ],
                ),
              ),
              // GestureDetector(
              //   onTap: () =>
              //       {Get.toNamed('/web_tabs/activity/synthesis?type=3')},
              //   child: Column(
              //     children: [
              //       Image.asset(
              //         'static/web/zhihuan.png',
              //         width: 60,
              //         fit: BoxFit.fitWidth,
              //       ),
              //       SizedBox(
              //         height: 5,
              //       ),
              //       Text(
              //         '置换',
              //         style: TextStyle(fontSize: 12),
              //       )
              //     ],
              //   ),
              // ),
              GestureDetector(
                  onTap: () => {
                     Get.dialog(
                AlertDialog(
                  backgroundColor: Colors.transparent,
                  content: Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(15.0),
                        child: Image.asset(
                          'static/qidai.png',
                          width: 250,
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                    ],
                  ),
                ),
              )
                    // Get.toNamed('/web_tabs/ranking/ranking_list')
                  },
                  child: Column(
                    children: [
                      Image.asset(
                        'static/web/paihang.png',
                        width: 60,
                        fit: BoxFit.fitWidth,
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        '排行榜',
                        style: TextStyle(fontSize: 12),
                      )
                    ],
                  ))
            ],
          ),
          SizedBox(
            height: 40,
          ),
          Container(
            height: 40,
            margin: EdgeInsets.symmetric(horizontal: 30),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                color: Color(0XFFF8F9FD)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: Obx(() => Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: _index.value == 0
                              ? Color(0XFF0F172B)
                              : Color(0XFFF8F9FD)),
                      child: GestureDetector(
                        onTap: () => {
                          SearchData.value = [],
                          getSearch('product'),
                          _index.value = 0
                        },
                        child: Text('数字藏品',
                            style: TextStyle(
                                fontSize: 15,
                                color: _index.value == 0
                                    ? Color(0XFFffffff)
                                    : Color(0XFF0F172B))),
                      ))),
                ),
                Expanded(
                  child: Obx(() => Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: _index.value == 1
                              ? Color(0XFF0F172B)
                              : Color(0XFFF8F9FD)),
                      child: GestureDetector(
                        onTap: () => {
                          getSearch('box'),
                          SearchData.value = [],
                          _index.value = 1
                        },
                        child: Text('数字盲盒',
                            style: TextStyle(
                                fontSize: 15,
                                color: _index.value == 1
                                    ? Color(0XFFffffff)
                                    : Color(0XFF0F172B))),
                      ))),
                ),
              ],
            ),
          ),
          Obx(()=>
          
          Column(
            children: [
                 for(var item in SearchData)
          GestureDetector(
            onTap: () => {
              if(item['is_draw']==1){
                  Get.toNamed('/web_tabs/details/draw_lots?draw=${item['is_draw']}&uuid=${item['uuid']}&is_box=${item['is_box']}')
              }else{
                Get.toNamed('/web_tabs/details/detail?is_box=${item['is_box']}&uuid=${item['uuid']}')
              }
              
              },
            child: Container(
              child: Column(
                children: [
                  SizedBox(
                    height: 20,
                  ),
                  Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(20),
                        child: Image.network(
                          '${item['thumb']}',
                          fit: BoxFit.fitWidth,
                        )),
                        if(!item['istime'])
                        Positioned(
                          top: 10,
                          right: 10,
                          child: 
                          Container(
                            padding: EdgeInsets.symmetric(vertical: 5,horizontal: 15),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: Color.fromARGB(128, 0, 0, 0)
                            ),
                            child:
                              Center(
                              child: CountdownTimer(
                                targetDate:item['targetDate'],
                              ),)
                            
                          )
                        )
                    ],
                  )
                 ,
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 10,),
                        Text(
                          '${item['title']}',
                          style:
                              TextStyle(fontSize: 18, color: Color(0XFF1F058C),fontWeight: FontWeight.bold),
                        ),
                        SizedBox(height: 5,),
                        Row(
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '限量',
                                  style: TextStyle(
                                      fontSize: 12, color: Color(0XFF999999)),
                                ),
                                Row(
                                  children: [
                                    Text(
                                     '${item['sell_num']}',
                                      style: TextStyle(
                                          fontSize: 18,
                                          color: Color(0XFF0F172B),
                                          fontWeight: FontWeight.bold),
                                    ),
                                    SizedBox(
                                      width: 5,
                                    ),
                                    Text(
                                      '份',
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0XFF999999)),
                                    ),
                                  ],
                                )
                              ],
                            ),
                            SizedBox(
                              width: 30,
                            ),
                            // Column(
                            //   crossAxisAlignment: CrossAxisAlignment.start,
                            //   children: [
                            //     Text(
                            //       '流通',
                            //       style: TextStyle(
                            //           fontSize: 12, color: Color(0XFF999999)),
                            //     ),
                            //     Row(
                            //       children: [
                            //         Text(
                            //           '1000',
                            //           style: TextStyle(
                            //               fontSize: 18,
                            //               color: Color(0XFF0F172B),
                            //               fontWeight: FontWeight.bold),
                            //         ),
                            //         SizedBox(
                            //           width: 5,
                            //         ),
                            //         Text(
                            //           '份',
                            //           style: TextStyle(
                            //               fontSize: 12,
                            //               color: Color(0XFF999999)),
                            //         ),
                            //       ],
                            //     )
                            //   ],
                            // ),
                            // SizedBox(
                            //   width: 30,
                            // ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '限价',
                                  style: TextStyle(
                                      fontSize: 12, color: Color(0XFF999999)),
                                ),
                                Row(
                                  children: [
                                    Text(
                                      '${item['money_price']/100}',
                                      style: TextStyle(
                                          fontSize: 18,
                                          color: Color(0XFF0F172B),
                                          fontWeight: FontWeight.bold),
                                    ),
                                    SizedBox(
                                      width: 5,
                                    ),
                                    Text(
                                      '元',
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0XFF999999)),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          
                          ],
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          
            ],
          )
         
          ),
        ],
      ),
    );
  }
}

class CarouselWithDots extends StatefulWidget {
  @override
  _CarouselWithDotsState createState() => _CarouselWithDotsState();
}

class _CarouselWithDotsState extends State<CarouselWithDots> {
  int _currentIndex = 0;
  final CarouselSliderController _carouselController =
      CarouselSliderController();

  RxList bannerData = [].obs;

  getbanner() {
    Get.find<HTTPS>().getData('/banner', {}).then((res) {
      bannerData.value = res;
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getbanner();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Obx(() => CarouselSlider(
              carouselController: _carouselController,
              items: bannerData.map((i) {
                return Builder(
                  builder: (BuildContext context) {
                    return Container(
                        alignment: Alignment.centerLeft,
                        width: MediaQuery.of(context).size.width,
                        margin: EdgeInsets.symmetric(horizontal: 0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15),
                            color: Color.fromARGB(255, 31, 57, 85)),
                        child: 
                            ClipRRect(
                              borderRadius: BorderRadius.circular(15.0), // 设置圆角大小
                              child: Image.network(
                               '${i['image']}',
                                width: MediaQuery.of(context).size.width,
                                height: 250,
                                fit: BoxFit.cover, // 根据需要调整图片的填充方式
                              ),
                            )
                    );
                       
                  },
                );
              }).toList(),
              options: CarouselOptions(
                height: 250,
                autoPlay: false,
                enlargeCenterPage: true,
                viewportFraction: 1,
                onPageChanged: (index, reason) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
              ),
            )),
        SizedBox(height: 10),
        Obx(() => Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: bannerData.asMap().entries.map((entry) {
                return GestureDetector(
                  onTap: () => _carouselController.animateToPage(entry.key),
                  child: Container(
                    width: 8.0,
                    height: 8.0,
                    margin: EdgeInsets.symmetric(horizontal: 4.0),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _currentIndex == entry.key
                          ? Color(0xff0F172B)
                          : Color(0xff999999),
                    ),
                  ),
                );
              }).toList(),
            )),
      ],
    );
  }
}

class MyCarousel extends StatelessWidget {
  RxList announcementData = [].obs;

  getAnnouncement() {
    Get.find<HTTPS>().getData('/announcement', {}).then((res) {
      announcementData.value = res;
    });
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getAnnouncement();
    });

    return Obx(() => CarouselSlider(
          options: CarouselOptions(
            scrollDirection: Axis.vertical,
            height: 19.0,
            aspectRatio: 16 / 9,
            viewportFraction: 1,
            initialPage: 0,
            enableInfiniteScroll: true,
            reverse: false,
            autoPlay: true,
            autoPlayInterval: Duration(seconds: 5),
            autoPlayAnimationDuration: Duration(milliseconds: 800),
            autoPlayCurve: Curves.fastOutSlowIn,
            pauseAutoPlayOnTouch: true,
          ),
          items: announcementData.map((i) {
            return Builder(
              builder: (BuildContext context) {
                return GestureDetector(
                  onTap: () {
                    Get.toNamed(
                        '/web_tabs/announcement/detail?uuid=${i['uuid']}');
                  },
                  child: Container(
                    alignment: Alignment.centerLeft,
                    width: MediaQuery.of(context).size.width,
                    margin: EdgeInsets.symmetric(horizontal: 0),
                    child: Text('${i['title']}',
                        style: TextStyle(
                            fontSize: 14.0,
                            fontWeight: FontWeight.bold,
                            overflow: TextOverflow.ellipsis)),
                  ),
                );
              },
            );
          }).toList(),
        ));
  }
}




class CountdownTimer extends StatefulWidget {
  final DateTime targetDate;
  
  const CountdownTimer({Key? key, required this.targetDate}) : super(key: key);

  @override
  _CountdownTimerState createState() => _CountdownTimerState();
}

class _CountdownTimerState extends State<CountdownTimer> {
  late Timer _timer;
  Duration _remaining = Duration.zero;

  @override
  void initState() {
    super.initState();
    _startCountdownLoop();
  }

  void _startCountdownLoop() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        final now = DateTime.now();
        _remaining = widget.targetDate.difference(now);
        
        if (_remaining.isNegative) {
          _remaining = Duration.zero;
          timer.cancel();
        }
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _formatDuration(_remaining),
      style: TextStyle(fontSize: 16, color: Color(0XFFFFFFFF)),
    );
  }

  String _formatDuration(Duration duration) {
    // if (duration.isNegative) return "已过期";
     if(duration.inDays > 0){
       return "${duration.inDays}天 "
        "${duration.inHours.remainder(24)}时 "
        "${duration.inMinutes.remainder(60)}分 "
        "${duration.inSeconds.remainder(60)}秒";
    }else{
       return "${duration.inHours.remainder(24)}时 "
        "${duration.inMinutes.remainder(60)}分 "
        "${duration.inSeconds.remainder(60)}秒";
    }
  }
}